<template>
  <div class="userBox">
    <div v-if="!userToken || userToken==''">
      <div>
        <el-input
            v-model="phone"
            style="width: 350px;"
            size="large"
            placeholder="请输入后台绑定的手机号"
            maxlength="11"
            :prefix-icon="User"
            :clearable="true"
        />
      </div>
      <div style="position: relative">
        <el-input
            style="margin-top:20px;width: 350px;"
            v-model="code"
            size="large"
            placeholder="请输入验证码"
            maxlength="6"
            :prefix-icon="Cellphone"
            :clearable="true"
        />
        <el-button type="primary" style="position: absolute;right:10px;top:24px;" plain @click="dosendCode"
                   :disabled="codeDisabled" :loading="codeloading">获取验证码
        </el-button>
      </div>
      <el-button type="primary" style="width:100%;margin-top:30px;" size="large" :loading="dologin"
                 @click="dologinhandle">立即登录
      </el-button>
    </div>
    <div v-if="userToken" style="font-size:14px;">
      登录名：<strong>{{userInfo.user}}</strong>
      <el-button type="primary" style="width:100%;margin-top:30px;" size="large"  @click="logout">退出
      </el-button>
    </div>
  </div>
</template>
<script setup>
import {ref} from 'vue'
import {User, Cellphone} from '@element-plus/icons-vue'
import {useCounterStore} from '../store/user.js'
import {ElMessage} from 'element-plus'
import {userLogin, sendCode} from '../api/wz.js'
const store = useCounterStore();
const phone = ref('18683626865')
const code = ref('')
const codeDisabled = ref(false)
const codeloading = ref(false)
const dologin = ref(false)
const userToken = ref(store?.token)
const userInfo = ref(store?.userInfo)
//监听store
store.$subscribe((mutation, store) => {
  userToken.value = store.token
  userInfo.value = store.userInfo
})
const dosendCode = () => {

  //验证码手机格式
  if (!/^1[3456789]\d{9}$/.test(phone.value)) {
    ElMessage.error('手机格式错误')
  } else {
    codeDisabled.value = codeloading.value = true
    sendCode({userPhone: phone.value}).then(r => {

    }).catch(e => {
      codeDisabled.value = codeloading.value = false
    })
  }
}
const logout = () => {
  store.logout()
}
const dologinhandle = () => {
  if (!/^1[3456789]\d{9}$/.test(phone.value)) {
    ElMessage.error('手机格式错误')
  } else if (code.value.length != 6) {
    ElMessage.error('验证码格式错误')
  } else {
    dologin.value = true
    userLogin({phone: phone.value, code: code.value}).then(r => {
      store.doLogin(r.data)
      dologin.value = false
    }).catch(e => {
      dologin.value = false
    })
  }
}
</script>
<style lang="less" scoped>
.userBox {
  margin: 10px 0;
  padding: 0 20px;
  margin-bottom: 40px;
}
</style>
